package dex.micros_gdc

import java.text.DateFormat
import java.text.ParseException
import java.text.SimpleDateFormat

import dex.micros_gdc.common.SQLConstants

class SummaryController {
	static allowedMethods = [save: "POST", update: "POST", delete: "POST"]

	// Export service provided by Export plugin
	def exportService
	def grailsApplication  //inject GrailsApplication

	static DateFormat DF = new SimpleDateFormat("MM/dd/yyyy")

	def taskService

	def index() {
		redirect(action: "list", params: params)
	}

	def list(Integer max) {
		params.max = Math.min(max ?: 18, 100)

		def results = getTasks(params, params?.offset ?: 0, "L")

		exportTasks(params)

		[taskInstanceList: results,
		 taskInstanceTotal: results.totalCount,
		 projects: taskService.getProjects(),
		 developers: taskService.getDevelopers(),
		 testers: taskService.getTesters(),
		 receivedDateFrom:params.receivedDateFrom,
		 receivedDateTo:params.receivedDateTo,
		 findId:params.findId]
	}

	def search()  {
		redirect(action: "list", params: params)
	}

	def reopen(Long id){
		def task = Task.get(id)
		if (!task) {
			flash.message = message(code: 'default.not.found.message', args: [
				message(code: 'task.label', default: 'Task'),
				id
			])
			redirect(action: "list", params: params)
			return
		}

		def map = ["closedFlag":"N"]
		task.properties = map

		if (!task.save(flush: true)) {
			task.errors.allErrors.each { log.error(it) }
			redirect(action: "list", params: params)
			return
		}

		flash.message = message(code: 'default.reopned.message', args: [
			message(code: 'task.label', default: 'Task'),
			task.id
		])
		redirect(action: "list", params: params)
	}

	def close(Long id){
		def task = Task.get(id)
		if (!task) {
			flash.message = message(code: 'default.not.found.message', args: [
				message(code: 'task.label', default: 'Task'),
				id
			])
			redirect(action: "list", params: params)
			return
		}

		def map = ["closedFlag":"Y"]
		task.properties = map

		if (!task.save(flush: true)) {
			task.errors.allErrors.each { log.error(it) }
			redirect(action: "list", params: params)
			return
		}

		flash.message = message(code: 'default.close.message', args: [
			message(code: 'task.label', default: 'Task'),
			task.id
		])
		redirect(action: "list", params: params)
	}

	private def exportTasks(params){
		def results = getTasks(params, 0, "E")

		if(params?.format && params.format != "html"){
			response.contentType = grailsApplication.config.grails.mime.types[params.format]
			response.setHeader("Content-disposition", "attachment; filename=tasks.${params.extension}")

			List fields = [
				"projectName",
				"activityNumber",
				"feedbackNumber",
				"receivedDate",
				"dueDate",
				"completedDate",
				"actionType",
				"documentType",
				"status",
				"ptsHour",
				"estimateHour",
				"rootCause",
				"developer",
				"tester",
				"comments",
				"testByGDCFlag",
				"closedFlag"
			]

			Map labels = [
				"projectName":"Project Name",
				"activityNumber": "Activity #",
				"feedbackNumber": "FB #",
				"receivedDate":"Received Date",
				"dueDate": "Due Date",
				"completedDate": "Completed Date",
				"actionType":"Action Type",
				"documentType":"Doc Type",
				"status":"Status",
				"ptsHour":"PTS",
				"estimateHour":"GDC",
				"rootCause":"Root Cause",
				"developer" :"DEV",
				"tester":"QA",
				"comments":"Comments",
				"testByGDCFlag":"GDC QA",
				"closedFlag":"Closed?"]

			Map parameters = ["column.widths": [
					0.15,
					0.12,
					0.12,
					0.15,
					0.15,
					0.15,
					0.10,
					0.10,
					0.20,
					0.10,
					0.10,
					0.25,
					0.20,
					0.20,
					0.50,
					0.15,
					0.10
				]]
			exportService.export(params.format, response.outputStream, results, fields,labels,[:], parameters)
		}
	}

	private def getTasks(params, offset, type) {
		def receivedDateFrom = parseDate(params.receivedDateFrom)
		def receivedDateTo = parseDate(params.receivedDateTo)

		def max = "E".equals(type)? 100000 :params.max
		def results = Task.createCriteria().list(max: max, offset: offset) {
			if(params.projectName)
				eq("projectName", params.projectName)

			if(params.developer)
				eq("developer", params.developer)

			if(params.at)
				eq("actionType", params.at)

			if(params.tester)
				eq("tester", params.tester)

			if(params.ts)
				eq('status', params.ts)

			if(params.closed)
				eq("closedFlag", params.closed)

			if(receivedDateFrom)
				ge("receivedDate", receivedDateFrom)

			if(receivedDateTo)
				le("receivedDate", receivedDateTo)

			if(params.findId) {
				def findId = params.findId
				if(findId.toString().toLowerCase().startsWith("fb"))
					eq("feedbackNumber", findId.toString().substring(2))
				else
					eq("activityNumber", findId)
			}

			if (params?.max)
				maxResults(params.max as Integer)

			if (params?.offset)
				firstResult(params.offset as Integer)

			order(params?.sort?:"receivedDate", params?.order?:"desc")
		}

		return results
	}

	private Date parseDate(String dateString){
		if(dateString == null) {
			return null
		}

		try {
			return DF.parse(dateString)
		} catch(ParseException e) {
			return null;
		}
	}
}
